<template>
  <div class="system-settings">
    <div class="page-header">
      <h2>系统设置</h2>
    </div>

    <div class="setting-section">
      <h3>网站信息</h3>
      <el-form 
        ref="basicForm" 
        :model="basicSettings" 
        :rules="basicRules"
        label-width="120px"
        class="setting-form"
      >
        <el-form-item label="网站名称" prop="siteName">
          <el-input v-model="basicSettings.siteName" placeholder="请输入网站名称" />
        </el-form-item>
        <el-form-item label="网站标题" prop="siteTitle">
          <el-input v-model="basicSettings.siteTitle" placeholder="请输入网站标题" />
        </el-form-item>
        <el-form-item label="网站描述" prop="siteDescription">
          <el-input 
            v-model="basicSettings.siteDescription" 
            type="textarea"
            :rows="3"
            placeholder="请输入网站描述" 
          />
        </el-form-item>
        <el-form-item label="网站关键词" prop="siteKeywords">
          <el-input v-model="basicSettings.siteKeywords" placeholder="请输入网站关键词，用逗号分隔" />
        </el-form-item>
        <el-form-item label="网站Logo" prop="siteLogo">
          <el-upload
            class="logo-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeLogoUpload"
            :http-request="uploadLogo"
          >
            <img v-if="basicSettings.siteLogo" :src="basicSettings.siteLogo" class="logo-preview" />
            <el-icon v-else class="logo-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="版权信息" prop="copyright">
          <el-input v-model="basicSettings.copyright" placeholder="请输入版权信息" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveBasicSettings" :loading="basicLoading">
            保存设置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useSystemStore } from '@/stores/system'

// 响应式数据
const basicForm = ref()
const basicLoading = ref(false)
const systemStore = useSystemStore()

// 系统配置列表
const systemConfigs = ref([])

// 基础设置 - 这里会从数据库映射
const basicSettings = reactive({
  siteName: '',
  siteTitle: '',
  siteDescription: '',
  siteKeywords: '',
  siteLogo: '',
  copyright: ''
})

// 配置Key映射
const configKeyMap = {
  siteName: 'site_name',
  siteTitle: 'site_title', 
  siteDescription: 'site_description',
  siteKeywords: 'site_keywords',
  siteLogo: 'site_logo',
  copyright: 'copyright'
}

// 表单验证规则
const basicRules = {
  siteName: [
    { required: true, message: '请输入网站名称', trigger: 'blur' }
  ],
  siteTitle: [
    { required: true, message: '请输入网站标题', trigger: 'blur' }
  ]
}

// 方法
const loadSettings = async () => {
  try {
    basicLoading.value = true
    const configs = await systemStore.getSystemConfig()
    systemConfigs.value = configs
    
    // 映射配置到表单数据
    Object.keys(configKeyMap).forEach(settingKey => {
      const configKey = configKeyMap[settingKey]
      const config = configs.find(c => c.key === configKey)
      if (config) {
        basicSettings[settingKey] = config.value || ''
      }
    })
    
    ElMessage.success('设置加载成功')
  } catch (error) {
    console.error('加载设置失败:', error)
    ElMessage.error('设置加载失败')
  } finally {
    basicLoading.value = false
  }
}

const saveBasicSettings = async () => {
  if (!basicForm.value) return
  
  try {
    await basicForm.value.validate()
    basicLoading.value = true
    
    // 准备批量更新数据
    const updateConfigs = []
    Object.keys(configKeyMap).forEach(settingKey => {
      const configKey = configKeyMap[settingKey]
      const config = systemConfigs.value.find(c => c.key === configKey)
      if (config) {
        updateConfigs.push({
          id: config.id,
          value: basicSettings[settingKey]
        })
      }
    })
    
    // 调用批量更新API
    await systemStore.batchUpdateSystemConfig(updateConfigs)
    
    ElMessage.success('基础设置保存成功')
  } catch (error) {
    console.error('保存设置失败:', error)
    if (error.message && error.message !== 'false') {
      ElMessage.error('基础设置保存失败: ' + error.message)
    } else {
      ElMessage.error('基础设置保存失败')
    }
  } finally {
    basicLoading.value = false
  }
}

const beforeLogoUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

const uploadLogo = async (options) => {
  try {
    const file = options.file
    const reader = new FileReader()
    
    return new Promise((resolve, reject) => {
      reader.onload = async (e) => {
        try {
          basicSettings.siteLogo = e.target.result
          // 立即保存Logo到数据库
          const logoConfig = systemConfigs.value.find(c => c.key === 'site_logo')
          if (logoConfig) {
            await systemStore.updateSystemConfig(logoConfig.id, {
              value: e.target.result
            })
            ElMessage.success('Logo上传成功')
          }
          resolve()
        } catch (error) {
          ElMessage.error('Logo保存失败')
          reject(error)
        }
      }
      reader.onerror = reject
      reader.readAsDataURL(file)
    })
  } catch (error) {
    ElMessage.error('Logo上传失败')
    return Promise.reject(error)
  }
}

// 生命周期
onMounted(() => {
  loadSettings()
})
</script>

<style scoped>
.system-settings {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.settings-tabs {
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.setting-section {
  max-width: 800px;
}

.setting-section h3 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 16px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.setting-form {
  margin-top: 20px;
}

.form-tip {
  margin-left: 10px;
  color: #666;
  font-size: 12px;
}

.logo-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.logo-uploader:hover {
  border-color: #409eff;
}

.logo-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  display: block;
}

.logo-preview {
  width: 100px;
  height: 100px;
  object-fit: cover;
  display: block;
}

:deep(.el-tabs__header) {
  margin-bottom: 30px;
}

:deep(.el-tabs__item) {
  font-size: 14px;
  padding: 0 30px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

:deep(.el-checkbox) {
  margin-right: 0;
}
</style>
